package com.dz.tool.Service.Impl.quartz;

import com.dz.tool.Service.OracleServer;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QuartzMain implements CommandLineRunner {

    @Resource
    OracleServer oracleServer;

    @Override
    public void run(String... args) throws Exception {
//        startOne("每天凌晨05分执行一次", "每天凌晨05分执行一次", "0 5 0 * * ?");
//        executeNow("每天凌晨05分执行一次","每天凌晨05分执行一次");

//        startOne2("每10分钟执行一次", "每10分钟执行一次", "0 */10 * * * ?");
//        executeNow("每10分钟执行一次","每10分钟执行一次");

    }


    @Resource
    private Scheduler scheduler;

    /**
     * 启动定时任务
     * @param jobName 任务名称
     * @param jobGroup 任务组
     * @param cronExpression Cron 表达式
     * @throws SchedulerException 调度器异常
     */
    public void startOne(String jobName, String jobGroup, String cronExpression) throws SchedulerException {
        System.out.println("每天凌晨05分执行一次");
        JobDetail jobDetail = JobBuilder.newJob(DayOneJob.class)
                .withIdentity(jobName, jobGroup)
                .build();
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName + "Trigger", jobGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .build();
        scheduler.scheduleJob(jobDetail, trigger);
        if (!scheduler.isStarted()) {
            scheduler.start();
        }
    }

    public void startOne2(String jobName, String jobGroup, String cronExpression) throws SchedulerException {
        System.out.println("每10分钟执行一次");
        JobDetail jobDetail = JobBuilder.newJob(DayOneJob2.class)
                .withIdentity(jobName, jobGroup)
                .build();
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName + "Trigger", jobGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .build();
        scheduler.scheduleJob(jobDetail, trigger);
        if (!scheduler.isStarted()) {
            scheduler.start();
        }
    }

    /**
     * 立即执行指定任务
     * @param jobName 任务名称
     * @param jobGroup 任务组
     * @throws SchedulerException 调度器异常
     */
    public void executeNow(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroup);
        scheduler.triggerJob(jobKey);
    }

}
